<?php
namespace app\common\service;


use think\Db;
use think\Model;
use think\Request;

class TimingService extends BaseService
{
    /**
     * 定时任务，发送消息
     * @param $sid
     */
    public function SendMsg($sid){
        $this->SendVisitingMsg($sid);
        $this->SendCourseMsg($sid);
        return ['status' => 1];
    }
    /**
     * 给需要拜访客户的管理员发送消息
     * @param $sid
     * @return array
     * @throws \think\Exception
     */
    public function SendVisitingMsg($sid){
        $starttime = mktime(0,0,0,date('m'),date('d')+1,date('Y'));
        $endtime = mktime(23,59,59,date('m'),date('d')+1,date('Y'));
        $where = [
            'store_id' => $sid,
            'send_status' => 0
        ];
        $list = db('visiting')->where($where)->whereBetween('next_time',[$starttime,$endtime])->field('vid')->select();
        if(empty($list)){
            return ['status' => 1];
        }
        $tplServer = new WxTplMsgService();
        foreach($list as $v){
            $res= $tplServer->send($sid, $v['vid'], 'customer_visiting');
            if($res == true){
                db('visiting')->where(['vid' => $v['vid']])->update(['send_status' => 1]);
            }else{
                continue;
            }
        }

    }

    /**
     * 给领导发送每节课的报表
     * @param $sid
     */
    public function SendCourseMsg($sid){
        $where = [
            'sid' => $sid,
            'send_status' => 0,
            'schoolovertime' => ['<',time()]
        ];
        $course_list = db('course')->where($where)->field('courseid')->select();

        if(!empty($course_list)){
            $tplServer = new WxTplMsgService();
            foreach($course_list as $v){
                $res= $tplServer->send($sid, $v['courseid'], 'course_sign');
                if($res == true){
                    db('course')->where(['courseid' => $v['courseid']])->update(['send_status' => 1]);
                }else{
                    continue;
                }
            }
        }
    }

    /**
     * 给领导发送每个月报表
     * @param $sid
     */
    public function SendMonthMsg($sid){
        $statis_max_info = db('statis_month_sign')->where(['sid' => $sid])->order('os_month desc')->find();
        if(!$statis_max_info){
            $begin_schoolovertime = db('course')->order('schoolovertime asc')->value('schoolovertime');
            $start_time = is_numeric($begin_schoolovertime) ? $begin_schoolovertime : time();
        }else{
            $start_time = $statis_max_info['os_end_date'];
        }
        $data = array();
        $i = 1;
        $start_time = strtotime(date('Y-m-01 00:00:00', $start_time));
        $current_time = strtotime(date('Y-m-01 00:00:01',time()));
        while (($time = strtotime('-'.$i.' month',$current_time)) >= $start_time) {
            if (date('Ym',$start_time) == date('Ym',$time)) {
                //如果两个月份相等检查库是里否存在
                $statis = db('statis_month_sign')->where(['sid' => $sid,'os_month' => date('Ym',$start_time)]);
                if ($statis) {
                    break;
                }
            }
            $first_day_unixtime = strtotime(date('Y-m-01 00:00:00', $time));	//该月第一天0时unix时间戳
            $last_day_unixtime = strtotime(date('Y-m-01 23:59:59', $time)." +1 month -1 day"); //该月最后一天最后一秒时unix时间戳
            $key = count($data);
            $os_month = date('Ym',$first_day_unixtime);
            $data[$key]['os_month'] = $os_month;
            $data[$key]['os_start_date'] = $first_day_unixtime;
            $data[$key]['os_end_date'] = $last_day_unixtime;
            $data[$key]['sid'] = $sid;

            $info = db('statis_course_sign')->where(['sid' => $sid,'os_month'=>$os_month])
                ->field('count(*) as course_num,SUM(sign_ourclass_num) as sign_ourclass_num,SUM(sign_apply_num) as sign_apply_num,SUM(signed_ourclass_num) as signed_ourclass_num,SUM(signed_other_num) as signed_other_num')->select();

            $data[$key]['course_num']=intval($info[0]['course_num']);
            $data[$key]['sign_ourclass_num']=intval($info[0]['sign_ourclass_num']);
            $data[$key]['sign_apply_num']=intval($info[0]['sign_apply_num']);
            $data[$key]['signed_ourclass_num']=intval($info[0]['signed_ourclass_num']);
            $data[$key]['signed_other_num']=intval($info[0]['signed_other_num']);
            $data[$key]['addtime']=time();
            $i++;
        }
        if(!empty($data)&&is_array($data)){
            krsort($data);
            $res = db('statis_month_sign')->insertAll($data);
            if($res){
                $tplServer = new WxTplMsgService();
                $re= $tplServer->send($sid, $data[0]['os_month'], 'month_sign');
                if($re == true){
                    return ['status' => 1];
                }else{
                    return ['status' => 0];
                }
            }
        }else{
            return ['status' => 1];
        }
    }


    /**
     * 取消订单定时任务
     * @param $sid
     * @return array
     */
    public function cancelOrderTimingTask(){
        //半小时未支付的情况自动取消
        $cur_time = time();
        $effect_time = $cur_time - 1800;
        $field = 'o.sid,o.order_id,o.buyer_id,o.coupon_id,oc.course_id';
        $where = [
            'o.add_time' => ['<', $effect_time], //下单时间在有效期之前,则自动取消
            'o.status' => ['in', [0,5]] //待付款、线下支付待确认
        ];
        $order_list = db('order o')
                    ->join('order_course oc', 'o.order_id=oc.order_id')
                    ->field($field)
                    ->where($where)
                    ->select();
        $orderService = new OrderService();
        $err_order_ids = [];
        $wxTplMsgService = new WxTplMsgService();
        if($order_list){
            foreach($order_list as $k => $v){
                $r = $orderService->cancelOrderLogic($v['sid'], $v['buyer_id'], $v['order_id'], $v['course_id'], $v['coupon_id']);
                if($r['status'] == 0){
                    $err_order_ids[] = $v['order_id'];
                } else {
                    $course = db('course')->where(['courseid' => $v['course_id']])->find();
                    //给用户发送拒绝提醒
                    $wxTplMsgService->send($v['sid'], $v['buyer_id'], 'offline_payment_refuse', $course);
                }
            }
        }
        return ['status' => 1, 'msg' => '执行成功', 'data' => ['err_order_ids' => $err_order_ids]];
    }

}